package com.sgb.kjwl.view.ui.fragment;

import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.view.ui.adapter.category.CategoryLeftAdapter;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.databinding.FragmentCategory3Binding;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.category.CategoryMemberRightAdapter;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.member.ui.activity.MemberManageActivity;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelperNew;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.selection.CommonPopEntity;

import java.lang.reflect.Type;
import java.util.List;

public class CategoryMemberFragment extends AppLazyFragment {

    private FragmentCategory3Binding binding;
    private CategoryLeftAdapter leftAdapter;

    private int leftPos;

    public static CategoryMemberFragment newInstance() {
        CategoryMemberFragment fragment = new CategoryMemberFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_category3, container, false);
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        binding.actionBarTitle.setText("会员分类");
        binding.tabBar.setVisibility(View.GONE);

        leftAdapter = new CategoryLeftAdapter(getActivity(), null);
        binding.leftRecycler.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        binding.leftRecycler.setAdapter(leftAdapter);
        leftAdapter.setItemSelect(true);
        leftAdapter.setOnItemClick(new AdapterOnItemClick<MenuEntity<MenuEntity<MenuEntity>>>() {
            @Override
            public void onItemClick(MenuEntity<MenuEntity<MenuEntity>> entity3, int position) {
                leftPos = position;
                setRightAdapter(leftPos, entity3.getDatas());
                binding.rightRecycler.scrollToPosition(0);
            }
        });
        binding.rightRecycler.setPullRefreshEnabled(false);
        binding.rightRecycler.setLoadingMoreEnabled(false);
    }

    @Override
    protected void onLazyLoad() {
        getMemberCategoryModel();
    }

    /**
     * 获取会员全部分类
     */
    public void getMemberCategoryModel() {
        DialogHelperNew.showProgressDialog(getActivity(), "数据加载中...").setCanceledOnTouchOutside(false);
        Type type = new TypeToken<List<MenuEntity<MenuEntity<MenuEntity>>>>() {
        }.getType();
        Object object = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.CacheGoryMemberModel, type);
        if (null != object) {
            List<MenuEntity<MenuEntity<MenuEntity>>> cacheList = (List<MenuEntity<MenuEntity<MenuEntity>>>) object;
            if (cacheList.size() > 0) {
                showCategoryView(cacheList);
                DialogHelperNew.dismissProgressDialog();
            }
        }
        APIManager.getInstance().getCommonAPI().getMemberCategories().enqueue(new ICallBack<BaseEntity<List<MenuEntity<MenuEntity<MenuEntity>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<MenuEntity<MenuEntity<MenuEntity>>>> data) {
                DialogHelperNew.dismissProgressDialog();
                //获取缓存哈希值
                String mHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.CacheGoryMemberModel);
                //获取从网络请求下来的数据的哈希值
                String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                if (!mHash.equals(mHashNet)) {
                    showCategoryView(data.getData());
                    DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheGoryMemberModel, data.getData());
                }
            }
        });
    }

    private void showCategoryView(List<MenuEntity<MenuEntity<MenuEntity>>> cacheList) {
        if (cacheList != null && cacheList.size() > 0) {
            leftAdapter.setDefItem(0);
            leftAdapter.setDatas(cacheList);
            setRightAdapter(0, cacheList.get(0).getDatas());
        }
    }

    private void setRightAdapter(int leftPosition, List<MenuEntity<MenuEntity>> rightData) {
        CategoryMemberRightAdapter rightAdapter = new CategoryMemberRightAdapter(getActivity(), R.layout.item_category_member_right, rightData);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, RecyclerView.VERTICAL);
        binding.rightRecycler.setLayoutManager(layoutManager);
        if (binding.rightRecycler.getItemDecorationCount() > 0) {
            binding.rightRecycler.removeItemDecorationAt(0);
        }
        int spacing = (int) getResources().getDimension(R.dimen.dp5);
        binding.rightRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int column = parent.getChildAdapterPosition(view) % 2;
                if (column == 0) {
                    outRect.left = 0;
                    outRect.right = spacing;
                } else {
                    outRect.left = spacing;
                    outRect.right = spacing * 2;
                }
            }
        });
        rightAdapter.setLefPosition(leftPosition);
        binding.rightRecycler.setAdapter(rightAdapter);
        rightAdapter.setItemSelect(true);
        rightAdapter.setOnItemClick(new AdapterOnItemClick<MenuEntity<MenuEntity>>() {
            @Override
            public void onItemClick(MenuEntity<MenuEntity> menuEntityMenuEntity, int position) {
                CommonPopEntity entity = new CommonPopEntity();
                entity.setNo(menuEntityMenuEntity.getId());
                entity.setTypeName(menuEntityMenuEntity.getName());
                entity.setCurPos(position);
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(getContext());
                } else {
                    MemberManageActivity.start(getContext(), leftPos, entity);
                }
            }
        });
    }
}